package trastienda.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import trastienda.excepcion.DAOExcepcion;
import trastienda.modelo.Categoria;
import trastienda.modelo.Producto;
import trastienda.modelo.Usuario;


@Repository
public class CategoriaDAOImpl implements CategoriaDAO{
	
	@PersistenceContext
	private EntityManager em;

	public void setEm(EntityManager em) {
		this.em = em;
	}
	
	@SuppressWarnings(value = "unchecked")
	public Collection<Categoria> listarCategorias() throws DAOExcepcion {
		Collection<Categoria> entities = new ArrayList<Categoria>();
		try {
			Query q = em.createNamedQuery("Categoria.seleccionarTodos");
			entities = q.getResultList();
		} catch (Exception e) {
			throw new DAOExcepcion(e.getMessage());
		}
		return entities;
	}
	
	
	@SuppressWarnings(value = "unchecked")
	public Categoria insertarCategoria(Categoria cat) throws DAOExcepcion {
		try {
			em.persist(cat);
		} catch (Exception e) {
			e.printStackTrace();
			throw new DAOExcepcion(e.getMessage());
		}
		return cat;
	}
	
	public Categoria obtenerPorIdCategoria(int idCategoria) throws DAOExcepcion {
		try {
			return em.find(Categoria.class, idCategoria);
		} catch (Exception e) {
			throw new DAOExcepcion(e.getMessage());
		}
	}
	
	@SuppressWarnings(value = "unchecked")
	public Categoria modificarCategoria(Categoria cat) throws DAOExcepcion {
		try {
			em.merge(cat);
		} catch (Exception e) {
			throw new DAOExcepcion(e.getMessage());
		}
		return cat;
	}
	
	@SuppressWarnings(value = "unchecked")
	public void eliminarCategoria(Categoria cat) throws DAOExcepcion {
		try {
			Categoria r = em.find(Categoria.class, cat.getIdCategoria());
			em.remove(r);
		} catch (Exception e) {
			throw new DAOExcepcion(e.getMessage());
		}
		//eturn cat;
	}
	
	

}
